package com.kuang.lesson03.chat

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetSocketAddress

fun conversation(from: Int, to: Int): Job {
    println("conversation---" + Thread.currentThread().name)
    val socket = DatagramSocket(from)
    val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
    sendMsg(socket, to)
    return receiveMsg(socket, buffer)
}

private fun sendMsg(socket: DatagramSocket, port: Int) {
    GlobalScope.launch {
        println("sendMsg---" + Thread.currentThread().name)
        socket.use {
            while (true) {
                val msg = readLine()
                msg?.toByteArray()?.let {
                    val packet = DatagramPacket(it, it.size, InetSocketAddress("127.0.0.1", port))
                    socket.send(packet)
                }
                if ("bye" == msg) break
            }
        }
    }
}

private fun receiveMsg(socket: DatagramSocket, buffer: ByteArray) = GlobalScope.launch {
    println("receiveMsg---" + Thread.currentThread().name)
    socket.use {
        while (true) {
            val packet = DatagramPacket(buffer, buffer.size)
            socket.receive(packet)
            val msg = String(packet.data, 0, packet.length)
            println("${packet.port}: $msg")
            if ("bye" == msg) break
        }
    }
}
